package com.boot.utils;

import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

public class CreateHS512Key {
    // 密钥保存位置
    private static final String KEY_FILE = "jwt_hs512.key";

    public static SecretKey getSecretKey() throws IOException {
        Path path = Paths.get("src/main/java/com/boot/config/" + KEY_FILE);
        if (Files.exists(path)) {
            String base64Key = Files.readString(path);
            byte[] keyBytes = Base64.getDecoder().decode(base64Key);
            return Keys.hmacShaKeyFor(keyBytes);
        } else {
            SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);
            String base64Key = Base64.getEncoder().encodeToString(secretKey.getEncoded());
            Files.writeString(path, base64Key, StandardOpenOption.CREATE);
            return secretKey;
        }
    }
}
